let axios = require("utils/util.js")
let md5 = require("utils/md5.js")
const SMSdk = require('utils/weapp-fp.js');
// const umengConfig = require('utils/umtrack-wx.js'); 

//注意：require 之后要立即初始化配置
SMSdk.initConf({
    organization: 'rdXOXowIPxaK59rtd9I9', //必填，组织标识，邮件中 organization 项
    publicKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCC5obhkG6cRwBNjxAM4x6eUJ8wWm0Okv0U4Bf3HNwkUuetjdwRkzgfpqEJfaTiwPSVFF52nXOjAZqkM96XYfTyipuVY9nFrzOdcoI9O', //js 文件是 v3.0.0 版本后必填，加密公钥，邮件中 publicKey 项
    //微信/支付宝小程序关闭蓝牙权限
    authConf: {
      location: false,
      bluetooth: false
    }
  }),


  //本地服务器地址

  //app.js
  App({
    data: {
      SMSdk: SMSdk,
    },
    // umengConfig: {
    //   appKey: '62c2538f05844627b5d59318', //由友盟分配的APP_KEY
    //   // 使用Openid进行统计，此项为false时将使用友盟+uuid进行用户统计。
    //   // 使用Openid来统计微信小程序的用户，会使统计的指标更为准确，对系统准确性要求高的应用推荐使用Openid。
    //   useOpenid: true,
    //   // 使用openid进行统计时，是否授权友盟自动获取Openid，
    //   // 如若需要，请到友盟后台"设置管理-应用信息"(https://mp.umeng.com/setting/appset)中设置appId及secret
    //   autoGetOpenid: true,
    //   debug: false, //是否打开调试模式
    //   uploadUserInfo: true // 自动上传用户信息，设为false取消上传，默认为false
    // },
    onShow() {
      // console.log(umengConfig);
    },

    onLaunch: function () {
      this.linkSocket()
    },
    linkSocket() {
      let that = this
      let webscorkent = "wss://socket.xunyinjiaoyou.com:2346"

      wx.connectSocket({
        url: webscorkent,
        header: {
          'content-type': 'application/json'
        },
        success() {
          that.initEventHandle()
        },
      })
    },


    initEventHandle() {
      let that = this;
      wx.onSocketMessage((message) => {
        let message_;
        message_ = JSON.parse(message.data);
        // console.log(message_);
        that.globalData.callback(message)
        message_.type == "getClientId" && wx.setStorageSync('getClientId', message_.result.clientId)
      })
      wx.onSocketOpen(() => {
        console.log('WebSocket连接打开，准备发送login信息')
        let heartCheck = {
          timeoutObj: null,
          serverTimeoutObj: null,
          reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
          },
          start: function () {
            this.timeoutObj = setTimeout(() => {
              let obj;
              obj = {
                type: "login",
                uid: that.globalData.user_id,
              }
              let objToStr = JSON.stringify(obj)
              wx.sendSocketMessage({
                data: objToStr,
                success(res) {
                  console.log("发送login成功", res);
                },
              });
              // this.serverTimeoutObj = setTimeout(() => {
              //   console.log('关闭');
              //   wx.closeSocket();
              // }, 5000);
            }, 5000);
          }
        };
        heartCheck.reset().start()
      })
      // wx.onSocketError(function (res) {
      //   console.log('WebSocket连接打开失败')
      //   that.reconnect()
      // })
      // wx.onSocketClose(function (res) {
      //   console.log('WebSocket 已关闭！')
      //   that.reconnect()
      // })
    },


    reconnect() {
      if (this.lockReconnect) return;
      this.lockReconnect = true;
      clearTimeout(this.timer)
      let that = this
      if (this.globalData.limit < 20) {
        this.timer = setTimeout(() => {
          that.linkSocket();
          that.lockReconnect = false;
        }, 3000);
        that.globalData.limit = that.globalData.limit + 1
      } else {
        this.globalData.socketStatus === 'connected'
      }
    },
    //关闭信道
    closeSocket() {
      if (this.globalData.socketStatus === 'connected') {
        wx.closeSocket({
          success: () => {
            this.globalData.socketStatus = 'closed'
          }
        })
      }
    },
    onLoad: function (options) {
      let _ = this;
      wx.login({ //获取code
        success: res => {
          console.log(res);
          let timestamp = (Date.parse(new Date()) / 1000).toString();
          let params = {
            code: res.code,
            time: timestamp,
            type: "2",
            sign: md5.hexMD5(_token),
          };
          axios.axios({
            url: "/index/getOpenId",
            data: params
          }).then((res) => {
            _.globalData.openid = res.data.result.openid;
            _.globalData.unionid = res.data.result.unionid;
            wx.setStorageSync('unionid', res.data.result.unionid)
          })
        }
      });
    },
    user_info: function (page) {
      console.log('老用户登录');
      // let that = this;
      let promise = new Promise((resolve, reject) => {
        wx.login({ //获取code
          success: res => {
            let timestamp = (Date.parse(new Date()) / 1000).toString();
            let arys = {
              code: res.code,
              type: "2",
              time: timestamp,
            };
            let _token = axios.encryption(arys);
            let params = {
              code: res.code,
              time: timestamp,
              type: "2",
              sign: md5.hexMD5(_token),
            };
            axios.axios({
              url: "/index/getOpenId",
              data: params
            }).then((res) => {
              // console.log(res);
              this.globalData.openid = res.data.result.openid;
              this.globalData.unionid = res.data.result.unionid;
              wx.setStorageSync('unionid', res.data.result.unionid)
              var p = new Promise(function (resolve, reject) {
                wx.getSetting({
                  success: res => {
                    if (res.authSetting['scope.userInfo']) {
                      // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                      wx.getUserInfo({
                        success: res => {
                          resolve(res.userInfo);
                        }
                      })
                    }
                  }
                })
              });
              let that = this;
              p.then(function (user) {
                // console.log(user);
                let timestamp = (Date.parse(new Date()) / 1000).toString();
                let data = {
                  "city": user.city,
                  "country": user.country,
                  "headimgurl": user.avatarUrl,
                  "nickname": user.nickName,
                  "openid": res.data.result.openid,
                  "province": user.province,
                  "sex": user.gender,
                  "unionid": res.data.result.unionid
                }
                let arys = {
                  data: JSON.stringify(data),
                  type: "1",
                  time: timestamp,
                };
                let _token = axios.encryption(arys);
                let params = {
                  data: JSON.stringify(data),
                  type: "1",
                  time: timestamp,
                  sign: md5.hexMD5(_token),
                };
                axios.axios({
                  url: "/user/thirdLoginV2",
                  data: params
                }).then((res) => {
                  console.log("登录成功：", res);
                  if (res.data.status == 0) { //0
                    wx.showToast({
                      title: "登录成功",
                      icon: 'none',
                      duration: 2000 //持续的时间
                    })
                    wx.setStorageSync('UserInformation', res.data.result)
                    that.globalData.user_id = res.data.result.userId;
                    that.globalData.userToken = res.data.result.token;
                    that.globalData.perfectNumber = res.data.result.perfectNumber;
                    resolve(res.data.result);
                  } else {
                    wx.navigateTo({
                      url: '/pages/phone_login/phone_login?thirdLoginV2=' + '1',
                    })
                    // that.wxzhuce(res.data.result)
                  }
                })
              });

            })
          },
          fail(error) {
            reject(error)
          }
        })
      })
      return promise;
    },
    preventActive(fn) {
      const self = this
      if (this.globalData.PageActive) {
        this.globalData.PageActive = false
        if (fn) fn()
        setTimeout(() => {
          self.globalData.PageActive = true
        }, 1500); //设置该时间内重复触发只执行第一次，单位ms，按实际设置
      } else {
        console.log('重复点击或触发')
      }
    },
    //微信注册
    wxzhuce(nickname, sex, birthday, invitedId, headpic) {
      let _ = this;
      var m = new Promise(function (resolve, reject) {
        wx.login({ //获取code
          success: res => {
            console.log(res);
            let timestamp = (Date.parse(new Date()) / 1000).toString();
            let arys = {
              code: res.code,
              type: "2",
              time: timestamp,
            };
            let _token = axios.encryption(arys);
            let params = {
              code: res.code,
              time: timestamp,
              type: "2",
              sign: md5.hexMD5(_token),
            };
            axios.axios({
              url: "/index/getOpenId",
              data: params
            }).then((res) => {
              _.globalData.openid = res.data.result.openid;
              _.globalData.unionid = res.data.result.unionid;
              wx.setStorageSync('unionid', res.data.result.unionid)
              resolve();
            })
          }
        });
      })
      m.then(function () {
        let timestamp = (Date.parse(new Date()) / 1000).toString();
        let arys = {
          nickname: nickname,
          sex: sex,
          birthday: birthday,
          invitedId: invitedId,
          headpic: headpic,
          type: "1",
          openid: _.globalData.openid,
          unionid: _.globalData.unionid,
          time: timestamp,
        };
        let _token = axios.encryption(arys);
        let params = {
          nickname: nickname,
          sex: sex,
          birthday: birthday,
          invitedId: invitedId,
          headpic: headpic,
          type: "1",
          openid: _.globalData.openid,
          unionid: _.globalData.unionid,
          time: timestamp,
          sign: md5.hexMD5(_token),
          shumeiDeviceId: wx.getStorageSync('shumeiDeviceId'),
        };
        axios.axios({
          url: "/user/reg",
          data: params
        }).then((res) => {
          console.log(res.data);
          if (res.data.status == 0) {
            wx.showToast({
              title: res.data.result,
              icon: 'none',
              duration: 2000 //持续的时间
            })
            wx.setStorageSync('UserInformation', res.data.result)
            this.globalData.user_id = res.data.result.userId;
            this.globalData.userToken = res.data.result.token;
            this.globalData.perfectNumber = res.data.result.perfectNumber;
          } else {
            wx.showToast({
              title: res.data.result,
              icon: 'none',
              duration: 2000 //持续的时间
            })
          }
        })
      })
    },

    setWatcher(page) {
      let data = page.data; // 获取page 页面data
      let watch = page.watch;
      for (let i in watch) {
        let key = i.split('.'); // 将watch中的属性以'.'切分成数组
        let nowData = data; // 将data赋值给nowData
        let lastKey = key[key.length - 1];
        let watchFun = watch[i].handler || watch[i]; // 兼容带handler和不带handler的两种写法
        let deep = watch[i].deep; // 若未设置deep,则为undefine
        this.observe(nowData, lastKey, watchFun, deep, page); // 监听nowData对象的lastKey
      }
    },

    observe(obj, key, watchFun, deep, page) {
      let val = obj[key];
      // 判断deep是true 且 val不能为空 且 typeof val==='object'（数组内数值变化也需要深度监听）
      if (deep && val != null && typeof val === 'object') {
        for (let i in val) {
          this.observe(val, i, watchFun, deep, page); // 递归调用监听函数
        }
      }
      let that = this;
      Object.defineProperty(obj, key, {
        configurable: true,
        enumerable: true,
        set: function (value) {
          // 用page对象调用,改变函数内this指向,以便this.data访问data内的属性值
          watchFun.call(page, value, val); // value是新值，val是旧值
          val = value;
          if (deep) { // 若是深度监听,重新监听该对象，以便监听其属性。
            that.observe(obj, key, watchFun, deep, page);
          }
        },
        get: function () {
          return val;
        }
      })
    },



    globalData: {
      Sum_: 0,//未读信息 
      // umengConfig: umengConfig,
      SMSdk: SMSdk,
      callback: function () {},
      livePlayerList: [],
      shopId: {}, //全局scokent
      limit: 0,
      socketStatus: 'closed',
      PageActive: true,
      openid: '',
      unionid: '',
      zegoAppID: 160536944, // 填写自己账号下的AppID
      server: 'wss://webliveroom160536944-api.zego.im/ws', // 自己账号下的server
      userInfo: null,
      perfectNumber: null,
      userToken: "",
      user_id: null,
      AppSign: "0e473c7562d74475d9b9f5bb9daed499318ae34f17180c83acece1a496249794",
      IMtoken: "eJwtzM0KgkAUBeB3mXXkVeeKCu0MAltIRRi4GZ0xLuUP42Ba9O6ZujzfOZwPuxzP215pFjJnC2wzZ5KqNlTSzEJWVFNntDCNXgedfIi2JclCmwOgHQS*szRqaEmryRHRAYBFDVV-81zb5eiDu77QffqP8kJEHCge48wq0vI5JN247xMe13lmjW*dng5XlN4N-VezY98fzgo15g__",
    },
  })
